package com.hemaapp.yjnh.activity;

import java.util.ArrayList;

import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;
import xtom.frame.view.XtomRefreshLoadmoreLayout.OnStartListener;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.hemaapp.yjnh.adapter.CmnProductionAdapter;
import com.hemaapp.yjnh.adapter.SearchHistoryAdapter;
import com.hemaapp.yjnh.db.SearchDBClient;
import com.hemaapp.yjnh.listener.OnBlogItemClickListener;
import com.hemaapp.yjnh.bean.Blog;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog.OnButtonListener;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;

/**通用搜索
 * @author GuiyouZhang
 * Date：2016年1月10日 上午11:58:27
 * Email:guiyouzhang@163.com
 */
public class SearchActivity extends BaseActivity implements OnClickListener, SearchHistoryAdapter.OnHistoryClickListener {

	private EditText edit;
	private TextView cancel;
	private ListView lstvHistory;//搜索历史
	
	private RelativeLayout resultLayout;
	private RefreshLoadmoreLayout refreshLoadmoreLayout;
	private XtomListView lstvResult;
	private LinearLayout ll_return_top;//回顶部

	private ArrayList<String>search_strs=new ArrayList<String>();
	private SearchDBClient mClient;
	private SearchHistoryAdapter historyAdapter;
	private CmnProductionAdapter blogAdapter;
	private User user;
    private ArrayList<Blog> blogs = new ArrayList<>();//商品/助农列表

    private String keyword = "";
	private int page = 0;
	private String lat = "";//纬度
    private String lng = "";//经度
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_search);
		user = getApplicationContext().getUser();
		super.onCreate(savedInstanceState);
		lat = XtomSharedPreferencesUtil.get(mContext, "lat");
		lng = XtomSharedPreferencesUtil.get(mContext, "lng");
		mClient=new SearchDBClient(mContext);
		if (!isNull(keyword)) {//如果有传入关键词，直接进行搜索
			edit.setText(keyword);
            edit.setSelection(keyword.length());
		}
	}
	
	@Override
	protected void callBeforeDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
			case BLOG_LIST:
				showProgressDialog("请稍候");
				break;
		}
	}

	@Override
	protected void callAfterDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
			case BLOG_LIST:
				cancelProgressDialog();
				break;
		}
	}

	@Override
	protected void callBackForServerSuccess(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case BLOG_LIST:
			HemaPageArrayResult<Blog> bResult = (HemaPageArrayResult<Blog>) baseResult;
			if (bResult == null || bResult.getObjects() == null)
				return;
			ArrayList<Blog> goods = bResult.getObjects();
			if (page == 0) {// 刷新
				refreshLoadmoreLayout.refreshSuccess();
				refreshLoadmoreLayout.setLoadmoreable(true);
				blogs.clear();
				blogs.addAll(goods);
			}else {//加载更多
				refreshLoadmoreLayout.loadmoreSuccess();
				if (goods.size()>0) {
					blogs.addAll(goods);
				}else {
					refreshLoadmoreLayout.setLoadmoreable(false);
					XtomToastUtil.showShortToast(mContext, "已经到最后啦");
				}
			}
			refreshDatas(-1);
			ll_return_top.setVisibility(View.VISIBLE);
			break;
		}
	}

	@Override
	protected void callBackForServerFailed(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case BLOG_LIST:
			if (page == 0) {// 刷新
				refreshLoadmoreLayout.refreshFailed();
			}else {
				refreshLoadmoreLayout.loadmoreFailed();
			}
			XtomToastUtil.showShortToast(mContext, "获取信息失败，"+baseResult.getMsg());
			break;
		}
	}

	@Override
	protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
		case BLOG_LIST:
			if (page == 0) {// 刷新
				refreshLoadmoreLayout.refreshFailed();
			}else {
				refreshLoadmoreLayout.loadmoreFailed();
			}
			XtomToastUtil.showShortToast(mContext, "获取信息失败，请稍后再试");
            refreshDatas(failedType);
			break;
		}
	}

	/**刷新商品
	 * @param failedType
	 */
	private void refreshDatas(int failedType) {
		if (null == blogAdapter) {
            blogAdapter = new CmnProductionAdapter(mContext, blogs);
            blogAdapter.setItemClickListener(new OnBlogItemClickListener() {
                @Override
                public void onClickListener(int position) {
                    Intent it = BaseUtil.createBlogIntent(mContext, blogs.get(position).getType());
                    it.putExtra("blog_id", blogs.get(position).getId());
                    mContext.startActivity(it);
                }

                @Override
                public void onCartListener(final int position) {
                }
            });
            blogAdapter.setEmptyString("未搜索到结果");
            lstvResult.setAdapter(blogAdapter);
		}else {
            blogAdapter.notifyDataSetChanged();
		}
        blogAdapter.setFailtype(failedType);
	}

	@Override
	protected void findView() {
		edit = (EditText) findViewById(R.id.edt_search);
		cancel = (TextView) findViewById(R.id.cancel);
        lstvHistory=(ListView) findViewById(R.id.lstv_history);
		
		resultLayout = (RelativeLayout) findViewById(R.id.layout_result);
		refreshLoadmoreLayout = (RefreshLoadmoreLayout) findViewById(R.id.layout_refresh);
		lstvResult = (XtomListView) findViewById(R.id.listview);
		ll_return_top = (LinearLayout) findViewById(R.id.ll_return_top);//回到顶部
	}

	@Override
	protected void getExras() {
		keyword = mIntent.getStringExtra("keyword");
	}

	@Override
	protected void onResume() {
        new LoadDBTask().execute();
		super.onResume();
	}

	@Override
	protected void setListener() {
		ll_return_top.setOnClickListener(this);
		cancel.setOnClickListener(this);
		edit.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
					keyword = v.getText().toString();
					if (isNull(keyword)) {
						return true;
					}
					mInputMethodManager.hideSoftInputFromWindow(
							v.getWindowToken(), 0);
					startSearch(keyword, true);//去搜索
					return true;
				}
				return false;
			}
		});
		refreshLoadmoreLayout.setOnStartListener(new StartListener());
//        int ten = BaseUtil.dip2px(mContext, 10);
//        lstvResult.setPadding(0, ten, 0, 0);
//        lstvResult.setDividerHeight(ten);
	}

	@Override
	public void OnItemClickListener(String key) {
		startSearch(key, false);
	}

	@Override
	public void OnClearClickListener() {

		HemaButtonDialog lodialog = new HemaButtonDialog(mContext);
		lodialog.setText("确定要清除历史记录？");
		lodialog.setRightButtonText("确定");
		lodialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
		lodialog.setLeftButtonText("取消");
		lodialog.setButtonListener(new OnButtonListener() {

			@Override
			public void onRightButtonClick(HemaButtonDialog dialog) {
				mClient.clear();
				search_strs.clear();
				historyAdapter.notifyDataSetChanged();
				dialog.cancel();
			}

			@Override
			public void onLeftButtonClick(HemaButtonDialog dialog) {
				dialog.cancel();
			}
		});
	}

	private class StartListener implements OnStartListener {

		@Override
		public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
			page = 0;
			goWebSearch();
		}

		@Override
		public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
			page++;
			goWebSearch();
		}
	}

	/**判断是否添加到搜索历史，然后去服务器检索关键字
	 * @param str 关键字
	 * @param addhistory 是否添加到搜素历史
	 */
	public void startSearch(String str, boolean addhistory) {
		edit.setText(str);
        edit.setSelection(str.length());
		if (addhistory) {
			boolean found = false;
			if (search_strs != null && search_strs.size() > 0) {
				for (String hstr : search_strs) {
					if (hstr.equals(str)) {
						found = true;
						break;
					}
				}
			}

			if (!found) {
				if (search_strs == null)
					search_strs = new ArrayList<String>();
				search_strs.add(0, str);
				mClient.insert(str);
			}
		}
		keyword = str;
		goWebSearch();
	}

	private void goWebSearch() {
        lstvHistory.setVisibility(View.GONE);
		resultLayout.setVisibility(View.VISIBLE);
        getNetWorker().blogList("18", "0", "1", "1", keyword, "", "", "", "", "", lng, lat, "", "", page+"");
	}

	private class LoadDBTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			// XtomProcessDialog.show(mContext, R.string.loading);
		}

		@Override
		protected Void doInBackground(Void... params) {
			search_strs = mClient.select();
			return null;
		}

		@Override
		protected void onPostExecute(Void v) {
			if (search_strs == null || search_strs.size() == 0) {
				return;
			}
            historyAdapter=new SearchHistoryAdapter(mContext, search_strs, SearchActivity.this);
            lstvHistory.setAdapter(historyAdapter);
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ll_return_top:
			lstvResult.setSelection(0);
			break;
		case R.id.cancel:
			finish();
			break;
		}
	}
}
